/**
 * @Title: MatchFingerprintSyncLogin.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年12月30日 下午10:12:58
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.http.KJFileParams;
import org.kymjs.aframe.utils.StringUtils;

import android.content.Context;
import android.fpi.MtRfid;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android_serialport_api.FingerprintManager;
import android_serialport_api.FingerprintReader;
import android_serialport_api.FingerprintReader.OnGenCharExListener;
import android_serialport_api.FingerprintReader.OnGetImageExListener;
import android_serialport_api.FingerprintReader.OnSearchListener;
import android_serialport_api.FingerprintReader.OnUpImageExListener;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.utils.CodecUtils;

/**
 * @ClassName: MatchFingerprintSyncLogin
 * @Description: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年12月30日 下午10:12:58
 */
public class MatchFingerprintSyncLogic {

	private static final String TAG = "MatchFingerprintSyncLogic";
	public static final String SIGNIN_TYPE = "finger_type";
	public static final int SIGNIN_TYPE_FINGER = 0;
	public static final int SIGNIN_TYPE_PLATFORM = 1;
	public static final int SIGNIN_TYPE_CARD = 2;

	/** 单例 */
	private static MatchFingerprintSyncLogic mSingleInstace;

	public boolean mIsCallBack = true;// 是否有回调，此需要Handle
	public boolean mIsShowImage = false;// 是否显示图像
	public boolean mIsManager = false;// 判断是否是管理员,默认false--矫正人员，
	public boolean mIsDestory = false;//
	public Context mContext;
	public String mImei;
	public String mMachId;
	public KJDB mKjdb;
	public KJFileParams mParams;
	// 打开
	private Timer xTimer = null;
	private TimerTask xTask = null;
	private Handler xHandler;
	private Message mMessage;
	private int mCount;
	private List<FingerPrintBean> mFingerPrintBeans;
	private FingerprintReader mValidateFingerprint;
	private Handler mHandler;

	public synchronized static MatchFingerprintSyncLogic getInstance() {
		if (mSingleInstace == null) {
			mSingleInstace = new MatchFingerprintSyncLogic();
		}
		return mSingleInstace;
	}

	private MatchFingerprintSyncLogic() {
		init();
	}

	private void init() {
		if (mContext == null) {
			this.mContext = AppContext.getAppContext();
		}
		this.mImei = AppContext.getInstance().getImei();
		if (StringUtils.isEmpty(mImei)) {
			this.mImei = "864121017006490";
		}
		if (StringUtils.isEmpty(mMachId)) {
			this.mMachId = String.valueOf(AppContext.getInstance().getMachId());
		}
		if (mParams == null) {
			this.mParams = new KJFileParams();
		}
		if (mKjdb == null) {
			this.mKjdb = AppContext.getInstance().getKjdb();
		}
		if (mValidateFingerprint == null) {
			this.mValidateFingerprint = FingerprintManager.getInstance()
					.getNewAsyncFingerprint();
		}
		if (mMessage == null) {
			mMessage = new Message();
		}
	}

	// 初始化监听
	private void initListener() {
		// 判断返回时图片还是文字
		mValidateFingerprint
				.setOnGetImageExListener(new OnGetImageExListener() {
					@Override
					public void onGetImageExSuccess() {
						Log.i(TAG,
								"---->setOnGetImageExListener onGetImageExSuccess 001");
						if (mIsShowImage) {
							mValidateFingerprint.PS_UpImageEx();//
							Log.i(TAG,
									"---->setOnGetImageExListener onGetImageExSuccess 008");
						} else {
							mValidateFingerprint.PS_GenCharEx(1);
							Log.i(TAG,
									"---->setOnGetImageExListener onGetImageExSuccess 009");
						}
					}

					@Override
					public void onGetImageExFail() {
						Log.i(TAG,
								"---->setOnGetImageExListener onGetImageExFail 002");
						if (!mIsDestory) {
							mValidateFingerprint.PS_GetImageEx();
						}
					}
				});

		// 图片---返回的图片结果
		mValidateFingerprint.setOnUpImageExListener(new OnUpImageExListener() {
			@Override
			public void onUpImageExSuccess(byte[] data) {
				Log.i(TAG,
						"---->setOnGetImageExListener onUpImageExSuccess 010");
				Log.i(TAG, "---->setOnUpImageExListener up image data.length="
						+ data.length);
				mValidateFingerprint.PS_GenCharEx(1);
				mMessage.what = UIHelper.FINGERPRINT_UPIMAGE_SUCCESS;
				Bundle bundle = new Bundle();
				bundle.putByteArray(UIHelper.FINGERPRINT_SOURCE, data);
				mMessage.setData(bundle);
				send();
			}

			@Override
			public void onUpImageExFail() {
				Log.i(TAG, "---->setOnGetImageExListener onUpImageExFail 011");
				mMessage.what = UIHelper.FINGERPRINT_UPIMAGE_FAIL;
				send();
			}
		});

		// 文字---监听文字返回结果
		mValidateFingerprint.setOnGenCharExListener(new OnGenCharExListener() {
			@Override
			public void onGenCharExSuccess(int bufferId) {
				Log.i(TAG,
						"---->setOnGenCharExListener onGenCharExSuccess 012 bufferId:"
								+ bufferId);
				/*if (bufferId == 1) {
					mValidateFingerprint.PS_GetImageEx();
					mCount++;
					mMessage.what = UIHelper.FINGERPRINT_AGAIN;
					send();
				} else if (bufferId == 2) {
				}*/
				mValidateFingerprint.PS_Search(1, 1, 1024);
			}

			@Override
			public void onGenCharExFail() {
				Log.i(TAG, "---->setOnGenCharExListener onGenCharExFail 013");
				xTimerStop();
				mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
				send();
			}
		});

		// 搜索指纹
		mValidateFingerprint.setOnSearchListener(new OnSearchListener() {
			@Override
			public void onSearchSuccess(int pageId, int matchScore) {
				Log.i(TAG, "pageId=" + pageId + "    matchScore=" + matchScore);
				xTimerStop();
				mMessage.what = UIHelper.FINGERPRINT_SEARCH_SUCCESS;
				mMessage.arg1 = pageId;
				mMessage.arg2 = SIGNIN_TYPE_FINGER;
				send();
				Log.i(TAG,
						"---->setOnGenCharExListener setOnSearchListener " + 22);
			}

			@Override
			public void onSearchFail() {
				xTimerStop();
				mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
				send();
				Log.i(TAG, "---->setOnGenCharExListener onSearchFail " + 23);
			}
		});
	}
	
	private void initCard(){
		xTimer = new Timer(); 
		xHandler = new Handler() { 
			@Override 
	        public void handleMessage(Message msg) { 
				
				int[] sn=new int[8];
				if(MtRfid.getInstance().RfidGetSn(sn)==0){
					xTimerStop();
					int[] buffer=new int[4096];
					String cardNO = CodecUtils.conver8ByteTo10String(sn);
					Log.i(TAG, "---->initCard cardNO :" + cardNO);
					int pageId = getPageIdFormCardNO(cardNO);
					Log.i(TAG, "---->initCard pageId :" + pageId);
					if (pageId == -1) {
						mMessage.what = UIHelper.FINGERPRINT_SEARCH_FAIL;
						send();
					}else {
						mMessage.what = UIHelper.FINGERPRINT_SEARCH_SUCCESS;
						mMessage.arg1 = pageId;
						mMessage.arg2 = SIGNIN_TYPE_CARD;
						send();
					}
					
				}
	            super.handleMessage(msg); 
	        }
	    };
	    xTask = new TimerTask() { 
	        @Override 
	        public void run() {
	        	if (!mIsDestory && !mIsManager) {
	        		Message message = new Message(); 
	        		message.what = 1; 
	        		xHandler.sendMessage(message); 
				}
	        } 
	    }; 
	}

	/***
	 * 设置是否显示指纹图像
	 */
	public void showImage(boolean isShowImage) {
		this.mIsShowImage = isShowImage;
	}

	/***
	 * 是否有数据返回
	 */
	public void isCallBack(boolean isCallBack) {
		this.mIsCallBack = isCallBack;
	}

	/**
	 * 是否是工作人员，如果非工作人员，则关闭打卡功能，默认false
	 */
	public void isManager(boolean isManager) {
		this.mIsManager = isManager;
	}

	/***
	 * 设置是否注释
	 */
	public void isDestory(boolean isDestory) {
		this.mIsDestory = isDestory;
	}
	
	public void setFingerPrintReader(FingerprintReader fingerprintReader){
		this.mValidateFingerprint = fingerprintReader;
	}
	
	public void setHandle(Handler handler){
		this.mHandler = handler;
	}

	/***
	 * 执行
	 */
	public void execute() {
		mCount = 1;
		this.mIsDestory = false;
		initListener();
		if (!mIsManager) {
			initCard();
			xTimerStart();
		}
		validateFingerprintSync();
	}

	/***
	 * 返回处理结果
	 */
	public void send() {
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}
	}

	/***
	 * 注销
	 */
	public void destory() {
		mIsDestory = true;
		xTimerStop();
	}

	// 录入指纹
	private synchronized void validateFingerprintSync() {
		if (mValidateFingerprint != null) {
			mValidateFingerprint.PS_GetImageEx();
		}
	}

	// 开始打卡
	public void xTimerStart() {
		xTimer.schedule(xTask, 1000, 1000);
	}

	// 关闭
	public void xTimerStop() {
		if (xTimer != null && xTask != null) {
			xTimer.cancel();
			xTimer = null;
			xTask.cancel();
			xTask = null;
		}
	}

	// 根据监管卡号获取当前的pageId
	private int getPageIdFormCardNO(String cardNo) {
		if (StringUtils.isEmpty(cardNo)) {
			return -1;
		}
		try {
			mFingerPrintBeans = mKjdb.findAllByWhere(FingerPrintBean.class,
					" type = 1 and cardNo = '" + cardNo + "'");
		} catch (Exception e) {
			return -1;
		}
		if (mFingerPrintBeans != null && !mFingerPrintBeans.isEmpty()) {
			FingerPrintBean bean = mFingerPrintBeans.get(0);
			if (bean != null) {
				return bean.getId();
			}
		}
		return -1;
	}

}
